﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraGrid.Columns;
using pTools.cMethods;
using Entity.DbEntity;
using Newtonsoft.Json;
using pTools.PrintTable;

namespace pTools.TuQiangPrint
{
    public partial class NewPurchasePrint : DevExpress.XtraEditors.XtraForm
    {
        List<NewPurchaseListViewModel> models = new List<NewPurchaseListViewModel>();
        HttpAgreement http = new HttpAgreement();
        DBHelper db = new DBHelper();

        // Purchase 列表内数据内容为采购订单
        // Inventory 列表内数据内容为存货
        string sign = "";
        public NewPurchasePrint()
        {
            InitializeComponent();
            grid_WaterWash.DataSource = models;
            //AddDeleteRow();
        }

        private void gridView_printData_ShownEditor(object sender, EventArgs e)
        {
            if (sign == "sxb")
            {
                gridView_WaterWash.ActiveEditor.Properties.ReadOnly =
                (gridView_WaterWash.FocusedColumn.VisibleIndex != 2);
            }
            else if (sign == "ch")
            {
                gridView_WaterWash.ActiveEditor.Properties.ReadOnly =
                    (gridView_WaterWash.FocusedColumn.VisibleIndex != 2
                    && gridView_WaterWash.FocusedColumn.VisibleIndex != 5
                     && gridView_WaterWash.FocusedColumn.VisibleIndex != 6
                     && gridView_WaterWash.FocusedColumn.VisibleIndex != 7);
            }


        }

        private void gridView_WaterWash_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            GridView view = sender as GridView;

            if (e.Column != view.Columns["number"])
                return;

            e.Appearance.BackColor = Color.LightGreen;
        }

        void AddDeleteRow()
        {
            var column = new GridColumn
            {
                Caption = "删除",
                ShowButtonMode = DevExpress.XtraGrid.Views.Base.ShowButtonModeEnum.ShowAlways,
            };

            var buttonEdit = new DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit();

            buttonEdit.Buttons[0].Kind = DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph;
            buttonEdit.Buttons[0].Caption = "X";

            buttonEdit.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.HideTextEditor;

            buttonEdit.Buttons[0].ImageOptions.Image = Properties.Resources.Delete16;
            buttonEdit.AutoHeight = false;

            // 删除按钮事件
            buttonEdit.Click += (s, e) =>
            {
                gridView_WaterWash.DeleteRow(gridView_WaterWash.FocusedRowHandle);
            };

            column.ColumnEdit = buttonEdit;
            column.VisibleIndex = 10;
            column.Width = 25;
            column.FieldName = "DeleteRow";

            gridView_WaterWash.Columns.Add(column);
        }

        private void btn_deleteWaterWashCode_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gridView_WaterWash.DeleteSelectedRows();
        }

        private void btn_ClearWaterWashCode_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            clearList();
        }

        void clearList()
        {
            models.Clear();
            grid_WaterWash.RefreshDataSource();

            sign = "";
        }

        private void btn_exit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Application.Exit();
        }

        private void NewPurchasePrint_Load(object sender, EventArgs e)
        {
            // 加载模板和打印机
            LoadPrinterInfo();
            // 加载支持信息
            LoadSupportInfo();
            // 加载仓库
            //LoadWarehouse();
            QueryWarehouse();
        }

        void LoadSupportInfo()
        {
            barItem_supportCompany.Caption = Application.CompanyName;
            barItem_version.Caption = Application.ProductVersion;
        }

        void LoadPrinterInfo()
        {
            // 加载模板
            CommonMethods.loadPrintTemplte(cb_0_Template);
            // 加载打印机
            CommonMethods.loadPrintDevice(cb_0_Print);
        }

        void LoadWarehouse()
        {
            var sql_template = "select * from fun_WareHouse_Info where isDel = 0 and baseCode = '{0}'; ";
            var sql = string.Format(sql_template, CommonMethods.baseCode);

            var dt = db.getData(sql);

            cb_0_warehouse.ValueMember = "houseCode";
            cb_0_warehouse.DisplayMember = "houseName";
            cb_0_warehouse.DataSource = dt;
        }

        U8DbHelper u8Db = new U8DbHelper();
        void QueryWarehouse()
        {
            //var sql_template = "select * from fun_WareHouse_Info where isDel = 0 and baseCode = '{0}'; ";
            //var sql = string.Format(sql_template, CommonMethods.baseCode);

            //var dt = db.getData(sql);

            //cb_0_warehouse.ValueMember = "houseCode";
            //cb_0_warehouse.DisplayMember = "houseName";
            //cb_0_warehouse.DataSource = dt;

            var sql = "select * from Warehouse";
            var dt = u8Db.getData(sql);

            cb_0_warehouse.ValueMember = "cWhCode";
            cb_0_warehouse.DisplayMember = "cWhName";
            cb_0_warehouse.DataSource = dt;
            cb_0_warehouse.SelectedValue = "011-1";

            // 开始时，加载一遍货位
            if (cb_0_warehouse.Text!="")
            {
                var cWhCode = cb_0_warehouse.SelectedValue.ToString();
                QueryPosition(cWhCode);
            }
            
        }

        void QueryPosition(string cWhCode)
        {
            cb_0_position.SelectedValue = "";
            cb_0_position.SelectedText = "";

            cb_0_position.ValueMember = "cPosCode";
            cb_0_position.DisplayMember = "cPosName";

            var sql_temp = "select * from Position where cWhCode = '{0}'";
            var sql = string.Format(sql_temp, cWhCode);
            var dt = u8Db.getData(sql);

            cb_0_position.DataSource = dt;
        }

        private void gridView_WaterWash_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Column.VisibleIndex == 2)
            {
                tb_totalNum.Text = models.Sum(m => m.number).ToString();
            }
        }

        void ClearUnselectedRows()
        {
            // 清空水洗标列表中所有未选中的内容
            // 反选
            for (int i = 0; i < models.Count; i++)
            {
                gridView_WaterWash.InvertRowSelection(i);
            }

            // 删除
            gridView_WaterWash.DeleteSelectedRows();

            // 再反选
            for (int i = 0; i < models.Count; i++)
            {
                gridView_WaterWash.InvertRowSelection(i);
            }
        }

        private void btn_print_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (models.Count > 1)
            {
                ClearUnselectedRows();   //只有一条就不清空了，默认打印这条
            }
            #region 必填项验证
            if (string.IsNullOrEmpty(tb_totalNum.Text))
            {
                XtraMessageBox.Show("请填写数量");
                return;
            }
            //if (decimal.Parse(tb_proWeight.Text) == 0)
            //{
            //    XtraMessageBox.Show("打印重量不能为零，请填写重量");
            //    return;
            //}
            if (models.Count == 0)
            {
                XtraMessageBox.Show("至少添加一条记录");
                return;
            }
            if (string.IsNullOrEmpty(tb_customer.Text))
            {
                XtraMessageBox.Show("请选择客户");
                return;
            }
            //if (string.IsNullOrEmpty(cb_0_warehouse.SelectedValue.ToString()))
            //{
            //    XtraMessageBox.Show("请选择仓库");
            //    return;
            //}
            #endregion
            var count = int.Parse(tb_num.Text);
            for (int i = 0; i < count; i++)
            {
                var loopDic = new Dictionary<int, Dictionary<DbProductBar, List<DbSubBarCode>>>();
                var loop = int.Parse(tb_printNum.Text);

                Dictionary<DbProductBar, List<DbSubBarCode>> dic = new Dictionary<DbProductBar, List<DbSubBarCode>>();

                loopDic[loop] = dic;


                // 如果有勾选是否在库，状态是待出库
                // 反之是待入库
                var statusStr = cb_isIn.Checked ? "need-out" : "need-in";

                var warePosition = "";
                if (!string.IsNullOrWhiteSpace(cb_0_position.Text.ToString()))
                {
                    warePosition = cb_0_position.SelectedValue.ToString();
                }

                //（number不能取tb_totalNum.Text，tb_totalNum取的是列表全部总和，但是可能存在勾选部分行的情况）
                var bar = new DbProductBar
                {
                    proWeight = tb_proWeight.Text,
                    warePosition = warePosition,
                    //number = tb_totalNum.Text,
                    number = models.Sum(s => s.number).ToString(),
                    createtime = CommonMethods.GetTimeStr(),
                    createuser = CommonMethods.userCode,
                    barStatus = statusStr,
                    wareHouse = cb_0_warehouse.SelectedValue.ToString(),
                    isInitial = "N",
                    happenDate = CommonMethods.GetDateStr(),
                    memo = tb_memo.Text,
                    status = "Y",
                    cu_customer = tb_customerName.Text
                };

                models.GroupBy(g => g.proCode).ToList().ForEach((pm) =>
                {
                    bar.proCode += pm.First().proCode;
                    bar.proCode += ",";

                    bar.proName += pm.First().proName;
                    bar.proName += ",";
                });
                bar.proCode = bar.proCode.TrimEnd(',');
                bar.proName = bar.proName.TrimEnd(',');

                var subs = new List<DbSubBarCode>();

                foreach (var m in models)
                {
                    var s = new DbSubBarCode
                    {
                        color = m.proColor,
                        createtime = CommonMethods.GetTimeStr(),
                        createuser = CommonMethods.userCode,
                        customer = tb_customer.Text,
                        customerName = tb_customerName.Text,
                        number = m.number,
                        proCode = m.proCode,
                        proName = m.proName,
                        trademark = m.brand,

                        waterWashCode = m.outBarcode
                    };

                    subs.Add(s);
                }

                dic[bar] = subs;

                JsonSerializerSettings settings = new JsonSerializerSettings();
                settings.ContractResolver = new DictionaryAsArrayResolver();

                var json = SerializeObject<Dictionary<int, Dictionary<DbProductBar, List<DbSubBarCode>>>>(loopDic, settings);
                var jsonResult = http.PostJson("SavePurchaseBarCode", json);

                var rsl = JsonConvert.DeserializeObject<ReturnResult>(jsonResult);
                if (rsl.Result)
                {
                    settings = new JsonSerializerSettings();
                    settings.ContractResolver = new DictionaryAsArrayResolver();
                    var barCodes = DeserializeObject<List<string>>(rsl.Data.ToString(), settings);


                    foreach (var barCode in barCodes)
                    {
                        var dt_forPrint = new DataTable_ForPrint();
                        dt_forPrint.Datas = new List<KVP_Container>();
                        dt_forPrint.Columns = new List<string>
                        {
                            "barCode","happenDate","createtime","total","proCode",
                            "proName","color","number",
                            "wareHouse","proWeight","memo","customer","customerCode","trademark"//"waterWashCode"

                        };
                        var index = 0;
                        foreach (var pSub in subs)
                        {
                            // 条码
                            var kvp_barCode = new KVP
                            {
                                Key = "barCode",
                                Value = barCode
                            };

                            // 发生日期
                            var kvp_happenDate = new KVP
                            {
                                Key = "happenDate",
                                Value = bar.happenDate
                            };

                            // 打印时间
                            var kvp_createtime = new KVP
                            {
                                Key = "createtime",
                                Value = DateTime.Now.ToString()
                            };

                            // 合计
                            var kvp_total = new KVP
                            {
                                Key = "total",
                                Value = bar.number
                            };

                            // 存货编码
                            var kvp_proCode = new KVP
                            {
                                Key = "proCode",
                                Value = models[index].proCode
                            };

                            // 净重
                            var kvp_proWeight = new KVP
                            {
                                Key = "proWeight",
                                Value = bar.proWeight
                            };

                            // 备注
                            var kvp_memo = new KVP
                            {
                                Key = "memo",
                                Value = bar.memo
                            };

                            // 客户
                            var kvp_customer = new KVP
                            {
                                Key = "customer",
                                Value = tb_customerName.Text
                            };


                            // 水洗标
                            //var kvp_waterWashCode = new KVP
                            //{
                            //    Key = "waterWashCode",
                            //    Value = models[index].outBarcode
                            //};
                            var kvp_customerCode = new KVP
                            {
                                Key = "customerCode",
                                Value = models[index].outBarcode
                            };

                            // 颜色
                            var kvp_color = new KVP
                            {
                                Key = "color",
                                Value = models[index].proColor
                            };

                            // 存货名称
                            var kvp_proName = new KVP
                            {
                                Key = "proName",
                                Value = models[index].proName
                            };

                            // 数量
                            var kvp_number = new KVP
                            {
                                Key = "number",
                                Value = models[index].number.ToString()
                            };
                            // 商标
                            var kvp_trademark = new KVP
                            {
                                Key = "trademark",
                                Value = models[index].brand
                            };


                            var container = new KVP_Container();
                            container.kvps = new List<KVP>();

                            container.kvps.Add(kvp_barCode);
                            container.kvps.Add(kvp_happenDate);
                            container.kvps.Add(kvp_createtime);
                            container.kvps.Add(kvp_total);
                            container.kvps.Add(kvp_proCode);
                            container.kvps.Add(kvp_proWeight);
                            container.kvps.Add(kvp_memo);

                            //container.kvps.Add(kvp_waterWashCode);
                            container.kvps.Add(kvp_customerCode);
                            container.kvps.Add(kvp_color);
                            container.kvps.Add(kvp_proName);
                            container.kvps.Add(kvp_number);
                            container.kvps.Add(kvp_customer);

                            container.kvps.Add(kvp_trademark);

                            dt_forPrint.Datas.Add(container);
                            index++;
                        }
                        var printDt = dt_forPrint.GetPrintTable();

                        var message = "";
                        CommonMethods.DoPrint(printDt, cb_0_Template.Text, cb_0_Print.Text, ref message);
                    }
                }


            }


        }

        string GetInitWarehouseCode()
        {
            var sql = "select * from sys_parameters_info where parCode = 'InitWarehouseCode'";
            var dt = db.getData(sql);

            return dt.Rows[0]["parValue"].ToString();
        }

        public static string SerializeObject<T>(T value, JsonSerializerSettings settings)
        {
            if (value == null)
            {
                return null;
            }

            var dictionaryObject = new Dictionary<string, object> { { typeof(T).Name, value } };
            var jsonString = JsonConvert.SerializeObject(dictionaryObject, settings);

            return jsonString;
        }

        public static T DeserializeObject<T>(string jsonString, JsonSerializerSettings settings)
        {
            var objectValue = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonString, settings);
            return JsonConvert.DeserializeObject<T>(objectValue.Values.First().ToString(), settings);
        }

        private void tb_customerName_Click(object sender, EventArgs e)
        {
            var selCus = new SelectCustomer();
            selCus.ShowDialog();
            if (selCus.selectedCustomer != null)
            {
                var customer = selCus.selectedCustomer;

                tb_customer.Text = customer.cuCode;
                tb_customerName.Text = customer.cuName;
            }
        }

        private void btn_addPro_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (sign == "Purchase")
            {
                DialogResult dialogResult = MessageBox.Show("添加存货数据，需要清除当前采购订单信息，是否继续？", "清除采购订单信息", MessageBoxButtons.YesNo);

                if (dialogResult == System.Windows.Forms.DialogResult.Yes)
                {
                    clearList();
                    sign = "Inventory";

                    var selectInvtory = new NewSelectInventory();
                    selectInvtory.ShowDialog();

                    if (selectInvtory.selectedList
                        .Count == 0)
                    {
                        return;
                    }

                    var list = selectInvtory.selectedList;

                    foreach (var model in list)
                    {
                        var im = new NewPurchaseListViewModel
                        {
                            brand = "",
                            createtime = "",
                            createuser = "",
                            outBarcode = "",
                            proCode = model.proCode,
                            proColor = "",
                            proName = model.proName,
                            xianggui = ""
                        };
                        models.Add(im);
                    }

                    grid_WaterWash.RefreshDataSource();

                    tb_memo.Text = "存货打码";
                }
                
            }
            else
            {
                sign = "Inventory";

                var selectInvtory = new NewSelectInventory();
                selectInvtory.ShowDialog();

                if (selectInvtory.selectedList.Count == 0)
                {
                    return;
                }

                var list = selectInvtory.selectedList;

                foreach (var model in list)
                {
                    var im = new NewPurchaseListViewModel
                    {
                        brand = "",
                        createtime = "",
                        createuser = "",
                        outBarcode = "",
                        proCode = model.proCode,
                        proColor = "",
                        proName = model.proName,
                        xianggui = ""
                    };
                    models.Add(im);
                }

                grid_WaterWash.RefreshDataSource();

                tb_memo.Text = "存货打码";
            }


        }

        private void btn_refPurchaseOrder_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            // 如果标识是Purchase 不做处理
            // 如果标识是Inventory 提示添加采购数据 需要清理 存货数据

            if (sign == "Inventory")
            {
                DialogResult dialogResult = MessageBox.Show("添加采购订单数据，需要清除当前存货信息，是否继续？", "清除存货信息", MessageBoxButtons.YesNo);

                if (dialogResult == System.Windows.Forms.DialogResult.Yes)
                {
                    clearList();
                    sign = "Purchase";

                    var selectPurchase = new NewSelectPurchase();
                    selectPurchase.ShowDialog();

                    RenderListView(selectPurchase.selectedRows);

                    tb_totalNum.Text = models.Sum(m => m.number).ToString();
                    tb_memo.Text = "采购打码";
                }
            }
            else 
            {
                sign = "Purchase";

                var selectPurchase = new NewSelectPurchase();
                selectPurchase.ShowDialog();

                RenderListView(selectPurchase.selectedRows);

                tb_totalNum.Text = models.Sum(m => m.number).ToString();
                tb_memo.Text = "采购打码";
            }
        }

        void RenderListView(List<DataRow> rows)
        {
            foreach (var row in rows)
            {
                var nplv = new NewPurchaseListViewModel
                {
                    brand = row["cfree3"].ToString(),

                    number = int.Parse(row["iQuantity"].ToString()),
                    proCode = row["cInvCode"].ToString(),
                    proColor = row["cfree1"].ToString(),
                    proName = row["cInvName"].ToString(),

                };
                models.Add(nplv);

                grid_WaterWash.RefreshDataSource();
            }
        }

        private void cb_0_warehouse_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cb_0_warehouse.Text != "")
            {
                var cWhCode = cb_0_warehouse.SelectedValue.ToString();
                QueryPosition(cWhCode);
            }
            
        }
    }
}